package front

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"qihuang/protocol"
	"qihuang/service/front"
	"strconv"
)

type ArticleComment struct {
}

func (ArticleComment) CreateComment(c *gin.Context) {
	//articleId, err := strconv.Atoi(c.Param("article_id"))
	//if err != nil {
	//	c.JSON(http.StatusOK, gin.H{
	//		"status": 1,
	//		"msg":  err,
	//	})
	//	c.Abort()
	//	return
	//}
	u := front.Users{}
	var service front.CreateCommentService
	if err := c.ShouldBind(&service); err != nil {
		c.JSON(400, err.Error())
	} else {
		// 从前端传过来的headers的token解析出当前用户
		user := u.CurrentUser(c)
		res := service.Add(&user)
		c.JSON(200, res)
	}
}

//文章列表
func (ArticleComment) GetList(c *gin.Context) {
	resp := &protocol.Resp{Status: 0, Msg: "", Data: ""}
	articleId, err := strconv.Atoi(c.Param("article_id"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"status": 1,
			"msg":    err,
		})
		c.Abort()
		return
	}
	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil {
		page = 1
	}
	pageSize, err := strconv.Atoi(c.DefaultQuery("page_size", "10"))
	if err != nil {
		pageSize = 10
	}
	articleCommentServ := front.ArticleComments{}
	fields := []string{"id", "article_id", "reply_to_id", "content", "modify_time", "status", "parent_id", "root_id"}
	resp = articleCommentServ.GetListForEs(page, pageSize, articleId, fields)
	if resp.Status == -999 {
		resp = articleCommentServ.GetListForMysql(page, pageSize, articleId, fields)
	}
	c.JSON(http.StatusOK, resp)
}

//文章详情
func (ArticleComment) Show(c *gin.Context) {
	resp := &protocol.Resp{Status: 1, Msg: "", Data: ""}
	id, err := strconv.Atoi(c.Param("id"))
	articleServ := front.Articles{}
	if err != nil || id <= 0 {
		resp.Status = 1
		resp.Msg = "参数错误"
		c.JSON(http.StatusOK, resp)
		return
	}
	resp = articleServ.GetArticleDetail(id)
	c.JSON(http.StatusOK, resp)
}
